import { configureStore, combineReducers } from "@reduxjs/toolkit";

/**
 * persistReducer
 *    作用：对某个 reducer 做配置，生成一份新的处理了持久化的 reducer
 *    语法：
 *      const newReducer = persistReducer(config, xxReducer)
 *
 * persistStore
 *    作用：对整个 store 做一个包裹，生成一份数据，该数据需要给到 PersistGate 组件的 persistor 去使用
 *    语法：
 *      const persistor = persistStore(store)
 *
 *    PersistGate - 'redux-persist/integration/react'
 */
import { persistReducer, persistStore } from "redux-persist";
// import storage from "redux-persist/lib/storage/session"; // sessionStorage
import storage from "redux-persist/lib/storage"; // localStorage

// 引入切片文件中导出的 reducer
import app from "./modules/app";
import user from "./modules/user";

// 组装 rootReducer
const rootReducer = combineReducers({
  app: persistReducer(
    {
      key: "app", // 生成 storage 的 key，前缀为 "persist:", 最终 "persist:app"
      storage, // 配置 storage 使用 localStorage | sessionStorage
      // blacklist: ["user"], // 黑名单字段
    },
    app
  ),

  user: persistReducer(
    {
      key: "user",
      storage,
      blacklist: ["info", "menus", "menuTree"],
    },
    user
  ),
});

// 创建 store
const store = configureStore({
  reducer: rootReducer,
  // 配置不需要做序列化检查，主要处理使用了 redux-persist 后报错的一个小问题
  middleware: (getDefaultMiddleware) => {
    return getDefaultMiddleware({
      serializableCheck: false,
    });
  },
});

// 从 store 本身推断出 `RootState` 和 `AppDispatch` 类型
export type RootState = ReturnType<typeof store.getState>;
// 推断出类型: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;

// 具名导出给到 PersistGate 组件使用的 persistor
export const persistor = persistStore(store);

// 默认导出 store 实例
export default store;
